<template>
  <div>
    <div style="text-align: center;font-weight: bold;font-size: 2rem">
      在线聊天
    </div>
    <div class="chatBox">
      <el-row :gutter="12">
        <el-col :span="10" class="leftBar">
          <div style="font-size:1rem;font-weight: bold;text-align: center">
            当前会话
          </div>
          <div class="leftArea" v-if="userList.length===0">
            <div>
              暂无聊天
            </div>
          </div>
          <div v-else class="leftChatArea">
            <div v-for="(item,index) in userList" class="userMessageBox" :key="index">
              <img src="../../../assets/user.png" class="userAvatarImg">
              <div style="margin-left: 10px;flex:1">
                <div class="topUserInfo">
                  <div style="font-size: .6rem">
                    {{ item.username }}
                  </div>
                  <div style="flex:1;font-size: .5rem;color: gray;text-align: right">
                    {{ item.sendMessageTime }}
                  </div>
                </div>
                <div class="bottomUserInfo">
                  <div style="flex:1;font-size: .5rem" v-html="item.lastMessage">
                  </div>
                  <div class="messageDot" v-if="item.showMessageCount">
                    {{ item.messageCount }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="14" class="rightBar">
          <div class="chatArea">
            <div class="el-row--flex " style="justify-content: space-between;padding: 5px">
              <div>
                当前沟通用户:<span
                style="font-weight: bold">{{ currentUserName }}</span>
              </div>
              <el-button type="primary" size="small" @click="endTalk"> 结束会话</el-button>
            </div>
            <el-divider>聊天记录</el-divider>
            <div v-for="(item,index) in currentChatList">
              <div class="el-row--flex" style="margin:10px;align-items: center;justify-content: right"
                   v-if="item.fromId=== loginInfo.userId">
                <div>
                  <img src="@/assets/kefu.svg" class="avatarImg">
                </div>
                <div style="margin-left: 10px">
                  <div style="text-align: left;color: gray;font-size: .5rem">
                    {{ loginInfo.userName }}
                  </div>
                  <div class="chatContent">
                    <div v-html="item.sendContent">
                    </div>
                  </div>
                </div>
              </div>
              <div class="el-row--flex" style="margin:10px" v-else>
                <div>
                  <img src="@/assets/avatar.jpeg" class="avatarImg">
                </div>
                <div style="margin-left: 10px">
                  <div style="text-align: left;color: gray;font-size: .5rem">
                    {{ item.fromUserName }}
                  </div>
                  <div class="chatContent">
                    <div v-html="item.sendContent">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="chatInput">
            <div class="u-flex" style="justify-content: space-between">
              <el-button type="primary" @click="sendMessage">发送消息</el-button>
            </div>
            <el-input type="textarea" v-model="messageInput" style="margin-top: 10px">
            </el-input>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import {listChatMessage} from "@/api/chatMessage";
import axios from "@/utils/axios";

export default {
  data() {
    return {
      wsBaseUrl: "ws://192.168.31.186:9096/websocket/chat/",
      showIconPop: false,
      messageInput: "",
      ws: null,
      userList: [],
      currentUserId: -1,
      currentUserName: null,
      currentChatList: [],
      chatMessage: {
        id: null,
        fromId: null,
        toId: null,
        fromUserName: "",
        toUserName: "",
        sendContent: "",
        sendTime: {}
      },
      chatObj: {},
      iconList: [
        'el-icon-user-solid', 'el-icon-user',
        'el-icon-phone', 'el-icon-phone-outline',
        'el-icon-star-on', 'el-icon-star-off',
        'el-icon-s-goods', 'el-icon-goods'
      ],
      loginInfo: {
        userId: null,
        userName: null
      }
    }
  },
  name: "chat",
  methods: {
    sendMessage() {
      if (this.currentUserId === -1) {
        this.$message("当前无用户连接")
        return;
      }
      const chatMessage = {
        id: null,
        fromId: this.loginInfo.userId,
        toId: this.currentUserId,
        fromUserName: this.loginInfo.userName,
        toUserName: this.chatObj[`${this.currentUserId}`].userInfo.name,
        sendContent: this.messageInput.trim().toString(),
        sendTime: this.parseTime(new Date())
      }
      this.chatObj[`${this.currentUserId}`].chatList.push(chatMessage)
      this.ws.send(JSON.stringify(chatMessage));
      this.messageInput = "";
    },
    webSocketOpen() {
      this.$message({
        message: "上线",
        type: "success"
      })
    },
    webSocketClose(text) {
      this.$message({
        message: "下线",
        type: "error"
      })
      this.ws = null;
    },
    webSocketMessage(message) {
      this.chatMessage = JSON.parse(message.data);
    },

    initWebSocket() {
      const webSocketUrl = `${this.wsBaseUrl}${this.loginInfo.userId}`
      this.ws = new WebSocket(webSocketUrl);
      this.ws.onopen = this.webSocketOpen;
      this.ws.onmessage = this.webSocketMessage;
      this.ws.onclose = this.webSocketClose;
    },

    endTalk() {
      const chatMessage = {
        id: null,
        fromId: this.loginInfo.userId,
        toId: this.currentUserId,
        fromUserName: this.loginInfo.userName,
        toUserName: this.chatObj[`${this.currentUserId}`].userInfo.name,
        sendContent: "断开连接",
        sendTime: this.parseTime(new Date())
      }
      this.ws.send(JSON.stringify(chatMessage));
      this.userList = this.userList.filter(item =>
        item.userId !== this.currentUserId
      );
      this.currentChatList = [];
      this.currentUserName = "暂无用户";
      this.$delete(this.chatObj, this.currentUserId);
    },

    async handleChatMessage(newVal) {
      const userId = newVal.fromId === this.loginInfo.userId ? newVal.toId : newVal.fromId;
      //已有聊天记录,构建聊天的obj
      if (this.chatObj.hasOwnProperty(`${userId}`)) {
        const showMessageCount = (this.currentUserId !== userId)
        this.chatObj[`${userId}`].userInfo.showMessageCount = showMessageCount;
        if (showMessageCount) {
          this.chatObj[`${userId}`].userInfo.messageCount++;
        } else {
          this.chatObj[`${userId}`].userInfo.messageCount = 0;
        }
        this.chatObj[`${userId}`].userInfo.lastMessage = newVal.sendContent;
        this.chatObj[`${userId}`].userInfo.sendMessageTime = newVal.sendTime;
        this.chatObj[`${userId}`].chatList.push(newVal);
      } else {
        //新的聊天
        const userInfo = {
          userId: userId,
          username: newVal.fromId === this.loginInfo.userId ? newVal.toUserName : newVal.fromUserName,
          lastMessage: newVal.sendContent,
          sendMessageTime: newVal.sendTime,
          messageCount: 1,
          showMessageCount: true
        };
        const chatList = [];
        chatList.push(newVal);
        this.$set(this.chatObj, `${userId}`, {
          userInfo,
          chatList
        });
        this.userList.push(userInfo);
        if (Object.keys(this.chatObj).length === 1) {
          this.chatObj[`${userId}`].userInfo.showMessageCount = false;
          this.chatObj[`${userId}`].userInfo.messageCount = 0;
          this.currentUserId = userId;
          this.currentUserName = userInfo.username;
          this.currentChatList = chatList;
        }
      }
    }
  },
  async mounted() {
    const info = await axios.get('/adminUser/profile');
    this.loginInfo.userId = info.adminUserId;
    this.loginInfo.userName = info.nickName;
    this.initWebSocket();
  },
  computed: {},
  watch: {
    chatMessage: {
      async handler(newVal) {
        await this.handleChatMessage(newVal)
      }
    },
    currentUserId: {
      handler(newVal) {
        this.currentUserName = this.chatObj[`${newVal}`].userInfo.username;
        this.currentChatList = this.chatObj[`${newVal}`].chatList;
        this.chatObj[`${newVal}`].userInfo.showMessageCount = false;
        this.chatObj[`${newVal}`].userInfo.messageCount = 0;
      }
    }
  }
}
</script>


<style>
.chatBox {
  width: 80%;
  padding: 20px;
  margin: 20px;
  box-shadow: 0px 0px .1rem .1rem lightgray;
}

.leftBar {
  height: 500px;
  display: flex;
  flex-direction: column;

}

.leftArea {
  flex: 1;
  box-shadow: 0px 0px .1rem .1rem lightgray;
  display: flex;
  align-items: center;
  justify-content: center;
}

.leftChatArea {
  flex: 1;
  box-shadow: 0px 0px .1rem .1rem lightgray;
  scroll-behavior: auto;
  overflow: auto;
}

.userMessageBox {
  display: flex;
  margin: 10px;
  padding: 10px;
  border-radius: 10px;
  background-color: rgba(206, 212, 218, 0.97);
}

.userAvatarImg {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.topUserInfo {
  display: flex;
  align-items: center;

}

.bottomUserInfo {
  display: flex;
  margin-top: 10px;
}

.messageDot {
  background-color: red;
  color: white;
  border-radius: 50%;
  width: 15px;
  height: 15px;
  line-height: 15px;
  text-align: center;
  font-size: .4rem;
}

.rightBar {
  height: 500px;
  flex: 1;
  flex-direction: column;
}

.chatUserName {
  color: gray;
  font-size: 0.8rem;
}

.avatarImg {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.chatHeader {
  position: relative;
  background-color: skyblue;
  border-radius: 10px 10px 0px 0px;
  height: 50px;
}

.chatHeader div {
  position: absolute;
  right: 10px;
  top: 10px;
}

.chatArea {
  height: 400px;
  box-shadow: 0px 0px .1rem .1rem lightgray;
  overflow: auto;
  scroll-behavior: auto;
}

.chatInput {
  margin-top: 10px;
  flex: 1;
}

.chatContent {
  padding: 8px;
  margin: 8px;
  background-color: lightblue;
  border-radius: 10px;
  font-size: 0.9rem;
}

.messageBox {
  background-color: lightgray;
  margin: 10px;
  padding: 10px;
  border-radius: 10px;
  max-width: 80%;
  justify-content: flex-start;
  font-size: 0.9rem;
}


</style>
